import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { HeroService } from '../../services/hero.service';
import { StorageService } from '../../services/storage.service';
import { NzMessageService,NzModalService } from 'ng-zorro-antd';
import { NzFormatEmitEvent, NzTreeNodeOptions,NzTreeComponent } from 'ng-zorro-antd';
import { LogoimgSyncService, LogoimgSync } from '../../services/logoimg-async'


@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.scss', './theme.less']
})
export class MainComponent implements OnInit {

  @ViewChild('treeCom') treeCom: NzTreeComponent;
  public menuSearch: string;
  public name: string = "--";
  public logo: string = "assets/images/head.jpg";
  public company: string = "公司名称";
  public menulist: any;
  public hidebru: number;
  public hreadbru: Array<any> = [];
  public nodes: NzTreeNodeOptions[] = [];
  constructor(private heroService: HeroService,
              private storageService: StorageService,
              private router: Router,
              private message: NzMessageService,
              private modalService: NzModalService,
              private logoimgSyncService: LogoimgSyncService,
              private el: ElementRef) {
            }

  // 判断菜单只打开一列，保持页面清爽
  // openMap = {
  //   sub1: false,
  //   sub2: false,
  //   sub3: false,
  //   sub4: false,
  //   sub5: false,
  //   sub6: false
  // };
  // openHandler(value: string): void {
  //   for (const key in this.openMap) {
  //     if (key !== value) {
  //       this.openMap[key] = false;
  //     }
  //   }
  // }

  ngOnInit() {
    this.logoimgSyncService.info$.subscribe((info: LogoimgSync) => {
      this.logo = info.url;
    });
    this.getUserInfo();
    this.treeMenu();
  }

   // 获取用户信息
  getUserInfo() {
    let url = host + "/main/info";
    this.heroService.get(url).then(result => {
      this.name = result.data.name;
      if (result.data.merchant.logo) {
        this.logo = result.data.merchant.logo;
      }
      this.company = result.data.merchant.name;
      this.storageService.setItem('myUsername', name);
      this.storageService.setItem('type', result.data.type);
    })
  };

  //树结构菜单遍历
  treeMenu(){
    let url = host + "/main/menu";
    this.heroService.get(url).then(result => {

      // for循环遍历树状菜单
      this.menulist = result.data.filter((item) => item.isMenu);
      // console.log(this.menulist);
      this.nodes = [];
      for (let i = 0; i < this.menulist.length; i++) {
        if (this.menulist[i].level == 0) {
          this.nodes.push({ "title": this.menulist[i].name, "key": this.menulist[i].id, icon: this.menulist[i].icon, "url": this.menulist[i].url, isLeaf: true });
        }
      }

      for (let j = 0; j < this.menulist.length; j++) {
        if (this.menulist[j].level == 1) {
          for (let k = 0; k < this.nodes.length; k++) {
            if (this.menulist[j].pid == Number(this.nodes[k].key)) {
              delete this.nodes[k].isLeaf;
              this.nodes[k].expanded=false;
              if (!this.nodes[k].children) {
                this.nodes[k].children = [];
              }
              this.nodes[k].children.push({ "title": this.menulist[j].name, "key": this.menulist[j].id, "url": this.menulist[j].url, isLeaf: true });
            }
          }
        }
      }
      // console.log(this.nodes);
    })
  }

  // 左侧树状菜单点击事件功能
  nzEvent(event: NzFormatEmitEvent): void {
    if (event.node.origin.url) {
      this.router.navigate([event.node.origin.url]);
    }else{
      if(event.node.isExpanded){
        event.node.isExpanded=!event.node.isExpanded;
      }else{
        this.treeCom.getExpandedNodeList().map((item) => {
          item.isExpanded=false;
        })
        event.node.isExpanded=!event.node.isExpanded;
      }
    }
  }

  //查询菜单
  searchMenu(){
    if(!this.menuSearch){
      this.treeMenu();
    }else{
      let url = host + "/main/queryMenu?nameLike=" + this.menuSearch;
      this.heroService.get(url).then(result => {
        // console.log(result);
        // console.log(this.menulist);

        let menuSearchlist=result.data;
        // for循环遍历树状菜单
        this.nodes = [];
        let nodesSearch = [];
        for (let i = 0; i < this.menulist.length; i++) {
          if (this.menulist[i].level == 0) {
            nodesSearch.push({ "title": this.menulist[i].name, "key": this.menulist[i].id, icon: this.menulist[i].icon, "url": this.menulist[i].url, isLeaf: true });
            menuSearchlist.map( (item) => {
              if(item.id == this.menulist[i].id){
                this.nodes.push({ "title": item.name, "key": item.id, icon: item.icon, "url": item.url, isLeaf: true });
              }
            })
          }
        }
        // console.log(nodesSearch);
        // console.log(this.nodes);

        nodesSearch.map( (val) => {
          menuSearchlist.map( (item) => {
            if(item.pid == Number(val.key)){
              if(this.nodes.length > 0){
                this.nodes.map( (item2) => {
                  console.log(this.nodes);
                  if(item2.key !== val.key){
                    console.log(this.nodes);
                    this.nodes.push(val);
                  }
                })
              }else{
                this.nodes.push(val);
              }
            }
          })
        })

        this.nodes.map( (item1) => {
          menuSearchlist.map( (item2) => {
            if (item2.pid == Number(item1.key)) {
              delete item1.isLeaf;
              item1.expanded=true;
              if (!item1.children) {
                item1.children = [];
              }
              item1.children.push({ "title": item2.name, "key": item2.id, "url": item2.url, isLeaf: true });
            }
          })
        })

      })
    }
  }

  loginOut() {
    let url = host + "/main/loginout";
    this.heroService.get(url).then(result => {
      console.log(result);
      if (result.code == 0) {
        this.storageService.removeItem('token');
        this.storageService.removeItem('type');
        this.message.info('退出登录成功');
        this.router.navigate(['/login']);
      } else {
        this.modalService.error({
          nzTitle: '提示',
          nzContent: result.msg
        });
        this.router.navigate(['/login']);
      }
    })
  }

  onFocus() {
    this.el.nativeElement.querySelector('#menuInput').readOnly = false;
  }
}
